#include<iostream>
#include<string.h>
#include<unistd.h>
#include<pthread.h>

using namespace std;

void* thread1(void* args)
{
    cout<<"thread 1 returing"<<endl;
    int* ptr=(int*)malloc(sizeof(int));
    *ptr=1;
    return(void*)ptr;
}
void* thread2(void* args)
{
    cout<<"thread 2 exiting"<<endl;
    int* ptr=(int*)malloc(sizeof(int));
    *ptr=2;
    pthread_exit((void*)ptr);
}
void* thread3(void* args)
{
    while(true)
    {
        cout<<"thread 3 running"<<endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    //thread 1 return
    pthread_t tid;
    void* ret;
    pthread_create(&tid,nullptr,thread1,nullptr);
    pthread_join(tid,&ret);
    printf("Thread return,thread id:%x,return code:%d\n",tid,*(int*)ret);
    free(ret);
    //thread 2 exit
    pthread_create(&tid,nullptr,thread2,nullptr);
    pthread_join(tid,&ret);
    printf("thread return,thread id:%x,return code:%d\n",tid,*(int*)ret);
    free(ret);
    //thread 3 cancel by other
    pthread_create(&tid,nullptr,thread3,nullptr);
    sleep(3);
    pthread_cancel(tid);
    pthread_join(tid,&ret);
    if(ret == PTHREAD_CANCELED)
        printf("thread return,thread id:%x,return code:PTHREAD_CANCELED",tid);
    else
        printf("thread return,thread id:%x,retrun code:nullptr",tid);
    return 0;
}